<script setup lang="ts">
import { ref } from "vue";
import { LMarker } from "@vue-leaflet/vue-leaflet";
import { useMapStore } from "@/store";
import { queryPoints } from "@/api/pipe";
import { useLocalStore } from "@/views/inspection-plan/line/store";

const { L }: any = window;
const props = defineProps({
  map: {
    type: Object,
  },
  deviceCategoryManager: Object,
});
const pointListRef = ref([]);
const mapStore = useMapStore();
const { canSelectPipePointFlag } = storeToRefs(mapStore);
const localStore = useLocalStore();
const { visiblePointClassIds } = storeToRefs(localStore);

const onClick = (e: any) => {
  if (canSelectPipePointFlag.value) {
    const { pointId, pointName, latlng } = e.target.options.attribution;
    mapStore.setSelectedInspectionNode({
      pointId,
      pointName,
      coordinates: [latlng[1], latlng[0]],
    });
  }
};
const getIcon = (classId: string) => {
  const iconUrl = props.deviceCategoryManager.getIconUrl(classId);
  return L.icon({
    iconUrl,
    iconSize: [32, 32],
    iconAnchor: [16, 27],
  });
};
const getAllPoints = () =>
  queryPoints({ pageSize: 100000, pageIndex: 1, isPublish: true }).then(
    ({ data, errors, succeeded }: any) => {
      if (succeeded && Array.isArray(data?.items)) {
        pointListRef.value = data.items
          .filter((item: any) => item.jsonGeom)
          .map((item: any) => {
            const [lng, lat] = JSON.parse(item.jsonGeom).coordinates;
            return {
              ...item,
              icon: getIcon(item.classId),
              latlng: [lat, lng],
            };
          });
      }
    }
  );
onMounted(() => {
  getAllPoints();
});
watchEffect(() => {
  if (Array.isArray(visiblePointClassIds.value)) {
    pointListRef.value.forEach((item: any) => {
      item.visible = visiblePointClassIds.value.includes(item.classId);
    });
  } else {
    pointListRef.value.forEach((item: any) => {
      item.visible = true;
    });
  }
});
</script>

<template>
  <LMarker
    :key="pointId"
    v-for="{ latlng, pointId, pointName, icon } in pointListRef.filter(
      (item: any) => item.visible !== false
    )"
    :lat-lng="latlng"
    :icon="icon"
    @click="onClick"
    :attribution="{ pointId, pointName, latlng }"
  />
</template>

<style scoped lang="scss"></style>
